<!--
  * 商品表单
  *
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="closeDrawer">
    <template #closeIcon>
      <close @on-close="closeDrawer" />
    </template>
    <a-card title="基本资料" class="smart-margin-bottom10">
      <a-form ref="baseForm" :model="baseFormData" :rules="baseFormRules" :label-col="{ sm: 5, lg: 7 }" name="goodsForm">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :span="21">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="商品名称" name="goods_name">
                  <a-input v-model:value="baseFormData.goods_name" @change="transformPinyin" placeholder="填写后自动生成助记码" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="助记码" name="memo_code">
                  <a-input v-model:value="baseFormData.memo_code" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="商品分类" name="company_cate_id">
                  <CategoryTree v-model:value="baseFormData.company_cate_id" placeholder="请选择" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="所属品牌" name="company_brand_id">
                  <Select name="Brand" v-model:value="baseFormData.company_brand_id" placeholder="请选择" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item name="default_unit_type">
                  <template #label>
                    <a-space :size="2">
                      <span>默认单位</span>
                      <a-tooltip>
                        <template #title>
                          <div> 以默认单位货值金额为准 </div>
                          <div> 根据比例关系 </div>
                          <div> 实时计算各单位货值金额 </div>
                          <div> 默认单位不可停用规格 </div>
                        </template>
                        <QuestionCircleOutlined :style="{ color: themeColor }" />
                      </a-tooltip>
                    </a-space>
                  </template>
                  <a-radio-group style="white-space: nowrap" v-model:value="baseFormData.default_unit_type" @change="computedAgreePrice('base')">
                    <template v-for="item in goodsUnitTypeList" :key="item.value">
                      <a-radio-button :value="item.value">{{ item.desc }}</a-radio-button>
                    </template>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="标品类型" name="type">
                  <a-radio-group style="white-space: nowrap" v-model:value="baseFormData.type">
                    <a-radio-button :value="1">标品</a-radio-button>
                    <a-radio-button :value="2">非标品</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="保质期" name="shelf_life_day">
                  <a-input-number v-model:value="baseFormData.shelf_life_day" :min="0" :step="1" :precision="0" addonAfter="天" placeholder="请输入商品保质期(天)" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="排序" name="sort">
                  <a-input v-model:value="baseFormData.sort" placeholder="请输入排序" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="备注" name="remark">
                  <a-textarea :auto-size="{ minRows: 1, maxRows: 4 }" v-model:value="baseFormData.remark" placeholder="请输入商品备注" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="3">
            <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="" name="img">
                <FileUpload v-model:value="baseFormData.img" :default-file-list="baseFormData.img" buttonText="上传图片" :maxUploadSize="1" :maxSize="1" accept=".jpeg,.jpg,.png" />
              </a-form-item>
            </a-col>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card :tab-list="tabList" :active-tab-key="tabKey" :bordered="false" @tabChange="onTabChange" class="smart-margin-bottom10">
      <template #customTab="{ tab }">
        <div class="custom-tab">
          <span>{{ tab }}</span>
        </div>
      </template>
      <a-collapse class="smart-margin-bottom10" :activeKey="unitFormData.map(({ unit_type }) => unit_type)" v-show="tabKey === 'unit'">
        <a-collapse-panel :key="GOODS_UNIT_TYPE.SMALL.value" collapsible="disabled" :showArrow="false">
          <template #header>
            <a-space>
              <span>{{ getDescByValue('GOODS_UNIT_TYPE', GOODS_UNIT_TYPE.SMALL.value) }}</span>
              <a-tooltip>
                <template #title>
                  <div>小单位必须填写基本信息</div>
                  <div>不可停用/删除</div>
                </template>
                <QuestionCircleOutlined :style="{ color: themeColor }" />
              </a-tooltip>
              <a-tag color="processing" v-if="baseFormData.default_unit_type === GOODS_UNIT_TYPE.SMALL.value">默认单位</a-tag>
            </a-space>
          </template>
          <a-form ref="smallUnitForm" :model="smallUnitFormData" :rules="unitRules" name="unitForm_small" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="单位名称" name="unit_name">
                  <a-input v-model:value="smallUnitFormData.unit_name" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="规格名称" name="spec_name">
                  <a-input v-model:value="smallUnitFormData.spec_name" placeholder="请输入商品规格(如:220g)" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="商品条码" name="barcode">
                  <a-input v-model:value="smallUnitFormData.barcode" placeholder="请输入商品SKU" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="售价" name="sale_price">
                  <a-input-number v-model:value="smallUnitFormData.sale_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入商品售价" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="起购数" name="min_quantity">
                  <a-input-number v-model:value="smallUnitFormData.min_quantity" :min="1" :step="1" :precision="0" placeholder="请输入商品起购数">
                    <template #addonAfter v-if="smallUnitFormData.unit_name">
                      {{ smallUnitFormData.unit_name ?? '' }}
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="货值金额" name="agree_price">
                  <a-input-number v-model:value="smallUnitFormData.agree_price" @change="computedAgreePrice('small')" :min="0" :step="1" :precision="6" :disabled="baseFormData.default_unit_type !== GOODS_UNIT_TYPE.SMALL.value" addon-after="元" :placeholder="baseFormData.default_unit_type === GOODS_UNIT_TYPE.SMALL.value ? '请输入' : '自动计算'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="进价" name="cost_price">
                  <a-input-number v-model:value="smallUnitFormData.cost_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-collapse-panel>
        <a-collapse-panel :key="GOODS_UNIT_TYPE.MIDDLE.value" collapsible="disabled" forceRender :showArrow="false">
          <template #header>
            <a-space>
              <span>{{ getDescByValue('GOODS_UNIT_TYPE', GOODS_UNIT_TYPE.MIDDLE.value) }}</span>
              <a-tag color="processing" v-if="baseFormData.default_unit_type === GOODS_UNIT_TYPE.MIDDLE.value">默认单位</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-switch v-model:checked="middleUnitFormData.checked" :disabled="defaultUnitData?.unit_type === middleUnitFormData.unit_type" :loading="deleteUnitLoading.middleUnitFormData" checked-children="启用" un-checked-children="停用" />
          </template>
          <a-form ref="middleUnitForm" :model="middleUnitFormData" :rules="unitRules" name="unitForm_middle" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="单位名称" name="unit_name">
                  <a-input v-model:value="middleUnitFormData.unit_name" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="换算关系" name="conversion_rate">
                  <a-input-number v-model:value="middleUnitFormData.conversion_rate" :min="1" :step="1" placeholder="对应小单位数量">
                    <template #addonBefore v-if="middleUnitFormData.unit_name">
                      {{ middleUnitFormData.unit_name ? `1${middleUnitFormData.unit_name} =` : '' }}
                    </template>
                    <template #addonAfter v-if="smallUnitFormData?.unit_name">
                      {{ smallUnitFormData?.unit_name ?? '' }}
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="规格名称" name="spec_name">
                  <a-input v-model:value="middleUnitFormData.spec_name" placeholder="请输入商品规格(如:220g)" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="商品条码" name="barcode">
                  <a-input v-model:value="middleUnitFormData.barcode" placeholder="请输入商品SKU" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="售价" name="sale_price">
                  <a-input-number v-model:value="middleUnitFormData.sale_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="起购数" name="min_quantity">
                  <a-input-number v-model:value="middleUnitFormData.min_quantity" :min="1" :step="1" :precision="0" placeholder="请输入">
                    <template #addonAfter v-if="middleUnitFormData.unit_name">
                      {{ middleUnitFormData.unit_name ?? '' }}
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="货值金额" name="agree_price">
                  <a-input-number v-model:value="middleUnitFormData.agree_price" @change="computedAgreePrice('middle')" :min="0" :step="1" :precision="6" :disabled="baseFormData.default_unit_type !== GOODS_UNIT_TYPE.MIDDLE.value" addon-after="元" :placeholder="baseFormData.default_unit_type === GOODS_UNIT_TYPE.MIDDLE.value ? '请输入' : '自动计算'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="进价" name="cost_price">
                  <a-input-number v-model:value="middleUnitFormData.cost_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-collapse-panel>
        <a-collapse-panel :key="GOODS_UNIT_TYPE.LARGE.value" collapsible="disabled" forceRender :showArrow="false">
          <template #header>
            <a-space>
              <span>{{ getDescByValue('GOODS_UNIT_TYPE', GOODS_UNIT_TYPE.LARGE.value) }}</span>
              <a-tag color="processing" v-if="baseFormData.default_unit_type === GOODS_UNIT_TYPE.LARGE.value">默认单位</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-switch v-model:checked="largeUnitFormData.checked" :disabled="defaultUnitData?.unit_type === largeUnitFormData.unit_type" :loading="deleteUnitLoading.largeUnitFormData" checked-children="启用" un-checked-children="停用" />
          </template>
          <a-form ref="largeUnitForm" :model="largeUnitFormData" :rules="unitRules" name="unitForm_large" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="单位名称" name="unit_name">
                  <a-input v-model:value="largeUnitFormData.unit_name" placeholder="请输入商品单位名称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="换算关系" name="conversion_rate">
                  <a-input-number v-model:value="largeUnitFormData.conversion_rate" :min="1" :step="1" placeholder="对应小单位数量">
                    <template #addonBefore v-if="largeUnitFormData.unit_name">
                      {{ largeUnitFormData.unit_name ? `1${largeUnitFormData.unit_name} =` : '' }}
                    </template>
                    <template #addonAfter v-if="smallUnitFormData?.unit_name">
                      {{ smallUnitFormData?.unit_name ?? '' }}
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="规格名称" name="spec_name">
                  <a-input v-model:value="largeUnitFormData.spec_name" placeholder="请输入商品规格(如:220g)" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="商品条码" name="barcode">
                  <a-input v-model:value="largeUnitFormData.barcode" placeholder="请输入商品SKU" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="售价" name="sale_price">
                  <a-input-number v-model:value="largeUnitFormData.sale_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="起购数" name="min_quantity">
                  <a-input-number v-model:value="largeUnitFormData.min_quantity" :min="1" :step="1" :precision="0" placeholder="请输入">
                    <template #addonAfter v-if="largeUnitFormData.unit_name">
                      {{ largeUnitFormData.unit_name ?? '' }}
                    </template>
                  </a-input-number>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="货值金额" name="agree_price">
                  <a-input-number v-model:value="largeUnitFormData.agree_price" @change="computedAgreePrice('large')" :min="0" :step="1" :precision="6" :disabled="baseFormData.default_unit_type !== GOODS_UNIT_TYPE.LARGE.value" addon-after="元" :placeholder="baseFormData.default_unit_type === GOODS_UNIT_TYPE.LARGE.value ? '请输入' : '自动计算'" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="进价" name="cost_price">
                  <a-input-number v-model:value="largeUnitFormData.cost_price" :min="0" :step="1" :precision="6" addon-after="元" placeholder="请输入" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-collapse-panel>
      </a-collapse>
      <div v-show="tabKey !== 'unit'">
        <a-row :gutter="[{ sm: 8, md: 16, lg: 24 }, 10]">
          <a-col :span="24">
            <a-table size="small" :dataSource="unitFormData" :columns="unitColumns" rowKey="unit_type" :pagination="false" bordered :scroll="{ x: 'max-content' }">
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'unit_type'">
                  <a-space>
                    <a-tag :color="tagColor[text]">{{ getDescByValue('GOODS_UNIT_TYPE', text) }}</a-tag>
                    <a-tag color="processing" v-if="baseFormData.default_unit_type === text">默认单位</a-tag>
                  </a-space>
                </template>
                <template v-if="column.dataIndex === 'sale_price'">
                  {{ text ? Number(text).toFixed(2) : '' }}
                </template>
                <template v-if="column.dataIndex === 'conversion_rate'">
                  {{ `1${record.unit_name}=${text}${smallUnitFormData?.unit_name}` }}
                </template>
                <template v-if="column.dataIndex === 'agree_price'">
                  {{ text ? Number(text).toFixed(2) : '' }}
                </template>
                <template v-if="column.dataIndex === 'salesman_money'">
                  <a-form-item label="" name="salesman_money">
                    <a-input-number :value="record.salesman_money" @change="computeCommission($event as never, record, 'salesman_money')" addon-after="元" :min="0" :step="1" :precision="6" placeholder="业务提成" />
                  </a-form-item>
                </template>
                <template v-if="column.dataIndex === 'weight'">
                  <a-form-item label="" name="weight">
                    <a-input-number :value="record.weight" @change="computeBulkingValue($event as never, record, 'weight')" addon-after="kg" :min="0" :step="1" :precision="6" placeholder="输入重量" />
                  </a-form-item>
                </template>
                <template v-if="column.dataIndex === 'volume'">
                  <a-form-item label="" name="volume">
                    <a-input-number :value="record.volume" @change="computeBulkingValue($event as never, record, 'volume')" addon-after="m³" :min="0" :step="1" :precision="6" placeholder="输入体积" />
                  </a-form-item>
                </template>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </div>
    </a-card>

    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="closeDrawer">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { Modal, message } from 'ant-design-vue'
import _ from 'lodash'
import FileUpload from '@/components/support/file-upload/index.vue'
import CategoryTree from '@/components/business/select/cate-select.vue'
import Select from '@/components/business/select/index.vue'
import { goodsApi } from '@/api/business/shopping-mall/product-api'
import { searchApi } from '@/api/search/search-api'
import { errorSentry } from '@/lib/error-sentry'
import { GOODS_UNIT_TYPE, GOODS_CREATE_TYPE } from '@/constants/business/goods-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
const appConfigStore = useAppConfigStore()
const { getValueDescList, getDescByValue } = useEnums()
const goodsUnitTypeList = getValueDescList('GOODS_UNIT_TYPE')

// ========== 全局变量 ==========
const themeColor = ref(appConfigStore.$state.primaryColor)
const tagColor = {
  [GOODS_UNIT_TYPE.SMALL.value]: 'default',
  [GOODS_UNIT_TYPE.MIDDLE.value]: 'warning',
  [GOODS_UNIT_TYPE.LARGE.value]: 'success'
}

watch(appConfigStore, (newValue) => {
  themeColor.value = newValue.$state.primaryColor
})

// ========== 基础表单 START ==========
interface BaseFormData {
  // id
  id?: number
  // 商品名称
  goods_name: string
  // 助记码
  memo_code: string
  // 分类
  company_cate_id: number | undefined
  // 品牌
  company_brand_id: number | undefined
  // 保质期(天)
  shelf_life_day: number | undefined
  // 是否标品
  type: number
  // 默认规格
  default_unit_type: number
  // 排序
  sort: string
  // 备注
  remark: string
  // 商品图片
  img: string
  // 创建类型
  create_type: number
  // 收费类型
  charge_type: number
}
const baseFormRef = useTemplateRef('baseForm')
const baseFormRules = {
  goods_name: [{ required: true, message: '请输入商品名称', whitespace: true }],
  company_cate_id: [{ required: true, message: '请选择分类' }],
  company_brand_id: [{ required: true, message: '请选择品牌' }],
  dealer_id: [{ required: true, message: '请选择经销商' }],
  type: [{ required: true, message: '请选择是否标品' }],
  default_unit_type: [{ required: true, message: '请选择默认规格' }]
}
const defaultBaseFormData: BaseFormData = {
  // 商品名称
  goods_name: '',
  // 助记码
  memo_code: '',
  // 分类
  company_cate_id: undefined,
  // 品牌
  company_brand_id: undefined,
  // 保质期(天)
  shelf_life_day: undefined,
  // 是否标品
  type: 1,
  // 默认规格
  default_unit_type: GOODS_UNIT_TYPE.SMALL.value,
  // 排序
  sort: '',
  // 备注
  remark: '',
  // 商品图片
  img: '',
  // 创建类型
  create_type: GOODS_CREATE_TYPE.COMPANY.value,
  // 收费类型
  charge_type: 1 // 1:货值 2:计件
}
const baseFormData = ref<BaseFormData>(_.cloneDeep(defaultBaseFormData))
// ========== 默认单位 ==========
watch(
  () => baseFormData.value.default_unit_type,
  (type) => {
    if (type === GOODS_UNIT_TYPE.SMALL.value) {
      smallUnitFormData.value.checked = true
    }
    if (type === GOODS_UNIT_TYPE.MIDDLE.value) {
      middleUnitFormData.value.checked = true
    }
    if (type === GOODS_UNIT_TYPE.LARGE.value) {
      largeUnitFormData.value.checked = true
    }
  },
  { deep: true }
)
// ========== 助记码 ==========
const transformPinyin = _.debounce(async () => {
  if (baseFormData.value.goods_name) {
    const res = await searchApi.searchPinyin({ str: baseFormData.value.goods_name })
    if (res.data) {
      baseFormData.value.memo_code = res.data.code
    }
  }
}, 500)

// ========== 基础表单 END ==========

// ========== 卡片切换 ==========
const tabList = [
  {
    key: 'unit',
    tab: '单位信息'
  },
  {
    key: 'commission',
    tab: '配送提成'
  },
  {
    key: 'weight',
    tab: '重量/体积'
  }
]
type TabKey = 'unit' | 'commission' | 'weight'
const tabKey = ref<TabKey>('unit')
async function onTabChange(key: TabKey) {
  if (key === 'unit') {
    tabKey.value = key
    return
  }
  try {
    await smallUnitForm.value.validate()
    tabKey.value = key
  } catch (error) {
    message.error('请先添加规格')
  }
}

// ========== 规格表单 START ==========
interface UnitFormData {
  // id
  id?: number
  // 规格名称
  spec_name: string
  // 单位名称
  unit_name: string
  // 单位类型
  unit_type: number | undefined
  // 单位换算
  unit_convert: number | undefined
  // 换算比例
  conversion_rate: number | undefined
  // 规格图片
  spec_img: string
  // 商品条码
  barcode: string
  // 起购数
  min_quantity: number | undefined
  // 进价
  cost_price: number | undefined
  // 售价
  sale_price: number | undefined
  // 货值金额
  agree_price: number | undefined
  // 重量
  weight: number | undefined
  // 体积
  volume: number | undefined
  // 业务员提成
  salesman_money: number | undefined
  // 备注
  remark: ''
  // 是否启用
  checked: boolean
}
const defaultUnitFormData: UnitFormData = {
  // 规格名称
  spec_name: '',
  // 单位名称
  unit_name: '',
  // 单位类型
  unit_type: undefined,
  // 单位换算
  unit_convert: undefined,
  // 换算比例
  conversion_rate: undefined,
  // 规格图片
  spec_img: '',
  // 商品条码
  barcode: '',
  // 起购数
  min_quantity: undefined,
  // 进价
  cost_price: undefined,
  // 售价
  sale_price: undefined,
  // 货值金额
  agree_price: undefined,
  // 重量
  weight: undefined,
  // 体积
  volume: undefined,
  // 业务员提成
  salesman_money: undefined,
  // 备注
  remark: '',
  // 是否启用
  checked: true
}
const unitRules = {
  unit_name: [{ required: true, message: '单位名称不能为空' }],
  conversion_rate: [{ required: true, message: '单位换算不能为空' }],
  spec_name: [{ required: true, message: '规格名称不能为空' }],
  barcode: [{ required: true, message: '商品条码不能为空' }],
  // min_quantity: [{ required: true, message: '起购数不能为空' }],
  sale_price: [{ required: true, message: '售价不能为空' }],
  agree_price: [{ required: true, message: '货值金额不能为空' }]
}

// ========== 小单位 ==========
const smallUnitForm = useTemplateRef('smallUnitForm')
const smallUnitFormData = ref<UnitFormData>(resetSmallUnitForm())
function resetSmallUnitForm() {
  return Object.assign({}, defaultUnitFormData, { unit_type: GOODS_UNIT_TYPE.SMALL.value, conversion_rate: 1 })
}

// ========== 中单位 ==========
const middleUnitForm = useTemplateRef('middleUnitForm')
const middleUnitFormData = ref<UnitFormData>(resetMiddleUnitForm())
function resetMiddleUnitForm() {
  return Object.assign({}, defaultUnitFormData, { unit_type: GOODS_UNIT_TYPE.MIDDLE.value, checked: false })
}

// ========== 大单位 ==========
const largeUnitForm = useTemplateRef('largeUnitForm')
const largeUnitFormData = ref<UnitFormData>(resetLargeUnitForm())
function resetLargeUnitForm() {
  return Object.assign({}, defaultUnitFormData, { unit_type: GOODS_UNIT_TYPE.LARGE.value, checked: false })
}

// 监听换算比例自动回填规格字段
watch(
  () => [smallUnitFormData.value.spec_name, middleUnitFormData.value.conversion_rate, largeUnitFormData.value.conversion_rate],
  ([spec_name, middle_rate, large_rate]) => {
    if (middle_rate) {
      middleUnitFormData.value.spec_name = `${spec_name}*${middle_rate}`
    }
    if (large_rate) {
      largeUnitFormData.value.spec_name = `${spec_name}*${large_rate}`
    }
  }
)

// ========== 规格列表 ==========
const unitColumns = computed(() => {
  return [
    {
      title: '单位类型',
      dataIndex: 'unit_type'
    },
    {
      title: '规格',
      dataIndex: 'spec_name'
    },
    {
      title: '单位',
      dataIndex: 'unit_name'
    },
    {
      title: '起购数',
      dataIndex: 'min_quantity'
    },
    {
      title: '售价',
      dataIndex: 'sale_price'
    },
    {
      title: '比例关系',
      dataIndex: 'conversion_rate'
    },
    {
      title: '货值金额',
      dataIndex: 'agree_price'
    },
    {
      title: '业务提成',
      dataIndex: 'salesman_money',
      width: 160,
      disabled: !(tabKey.value === 'commission')
    },
    {
      title: '重量',
      dataIndex: 'weight',
      width: 160,
      disabled: !(tabKey.value === 'weight')
    },
    {
      title: '体积',
      dataIndex: 'volume',
      width: 160,
      disabled: !(tabKey.value === 'weight')
    }
  ].filter((item) => !item.disabled)
})
const unitFormData = computed(() => {
  return [smallUnitFormData.value, middleUnitFormData.value, largeUnitFormData.value].filter((item) => item.checked)
})

// ========== 更新规格数据 ==========
const defaultUnitData = computed(() => {
  return unitFormData.value.find((item) => item.unit_type === baseFormData.value.default_unit_type)
})
// 默认单位的货值金额
function computedAgreePrice(type: 'base' | 'small' | 'middle' | 'large') {
  function getBaseAgreePrice() {
    const agreePrice = Number(defaultUnitData.value?.agree_price)
    const conversionRate = Number(defaultUnitData.value?.conversion_rate)
    if (!_.isFinite(agreePrice) || !_.isFinite(conversionRate)) return undefined
    return _.divide(agreePrice, conversionRate)
  }
  let baseAgreePrice: number | undefined = getBaseAgreePrice()
  if (baseAgreePrice) {
    smallUnitFormData.value.agree_price = baseAgreePrice
    if (type !== 'middle' && _.isFinite(Number(middleUnitFormData.value.conversion_rate))) {
      middleUnitFormData.value.agree_price = _.multiply(baseAgreePrice, Number(middleUnitFormData.value.conversion_rate))
    }
    if (type !== 'large' && _.isFinite(Number(largeUnitFormData.value.conversion_rate))) {
      largeUnitFormData.value.agree_price = _.multiply(baseAgreePrice, Number(largeUnitFormData.value.conversion_rate))
    }
  }
}
watch(
  () => [defaultUnitData.value?.conversion_rate, middleUnitFormData.value.conversion_rate, largeUnitFormData.value.conversion_rate],
  ([default_rate]) => {
    if (default_rate) {
      computedAgreePrice('base')
    } else {
      smallUnitFormData.value.agree_price = undefined
      middleUnitFormData.value.agree_price = undefined
      largeUnitFormData.value.agree_price = undefined
    }
  },
  {
    deep: true
  }
)

// 配送、协送、业务提成
function computeCommission(value: number, { unit_type }: UnitFormData, name: 'salesman_money') {
  if (unit_type === GOODS_UNIT_TYPE.SMALL.value) {
    smallUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      if (middleUnitFormData.value.conversion_rate) {
        middleUnitFormData.value[name] = _.multiply(value, middleUnitFormData.value.conversion_rate)
      }
      if (largeUnitFormData.value.conversion_rate) {
        largeUnitFormData.value[name] = _.multiply(value, largeUnitFormData.value.conversion_rate)
      }
    }
  } else if (unit_type === GOODS_UNIT_TYPE.MIDDLE.value && middleUnitFormData.value.conversion_rate) {
    const baseNum = _.divide(value, middleUnitFormData.value.conversion_rate)
    middleUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      smallUnitFormData.value[name] = baseNum
      if (largeUnitFormData.value.conversion_rate) {
        largeUnitFormData.value[name] = _.multiply(baseNum, largeUnitFormData.value.conversion_rate)
      }
    }
  } else if (unit_type === GOODS_UNIT_TYPE.LARGE.value && largeUnitFormData.value.conversion_rate) {
    const baseNum = _.divide(value, largeUnitFormData.value.conversion_rate)
    largeUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      smallUnitFormData.value[name] = baseNum
      if (middleUnitFormData.value.conversion_rate) {
        middleUnitFormData.value[name] = _.multiply(baseNum, middleUnitFormData.value.conversion_rate)
      }
    }
  }
}

// 重量、体积
function computeBulkingValue(value: never, { unit_type }: UnitFormData, name: 'weight' | 'volume') {
  if (unit_type === GOODS_UNIT_TYPE.SMALL.value) {
    smallUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      if (middleUnitFormData.value.conversion_rate) {
        middleUnitFormData.value[name] = _.multiply(value, middleUnitFormData.value.conversion_rate)
      }
      if (largeUnitFormData.value.conversion_rate) {
        largeUnitFormData.value[name] = _.multiply(value, largeUnitFormData.value.conversion_rate)
      }
    }
  } else if (unit_type === GOODS_UNIT_TYPE.MIDDLE.value && middleUnitFormData.value.conversion_rate) {
    const baseNum = _.divide(value, middleUnitFormData.value.conversion_rate)
    middleUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      smallUnitFormData.value[name] = baseNum
      if (largeUnitFormData.value.conversion_rate) {
        largeUnitFormData.value[name] = _.multiply(baseNum, largeUnitFormData.value.conversion_rate)
      }
    }
  } else if (unit_type === GOODS_UNIT_TYPE.LARGE.value && largeUnitFormData.value.conversion_rate) {
    const baseNum = _.divide(value, largeUnitFormData.value.conversion_rate)
    largeUnitFormData.value[name] = value
    if (unit_type === baseFormData.value.default_unit_type) {
      smallUnitFormData.value[name] = baseNum
      if (middleUnitFormData.value.conversion_rate) {
        middleUnitFormData.value[name] = _.multiply(baseNum, middleUnitFormData.value.conversion_rate)
      }
    }
  }
}

// ========== 删除规格 ==========
const deleteUnitLoading = ref({
  middleUnitFormData: false,
  largeUnitFormData: false
})
function deleteSpec(name: 'middleUnitFormData' | 'largeUnitFormData', id?: number) {
  const deleteText = id ? '停用' : '清空'
  const unitNameMap = {
    middleUnitFormData: GOODS_UNIT_TYPE.MIDDLE.desc,
    largeUnitFormData: GOODS_UNIT_TYPE.LARGE.desc
  }
  Modal.confirm({
    title: `${deleteText}规格`,
    content: `确定要 ${deleteText} ${unitNameMap[name]} 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      deleteUnitLoading.value[name] = true
      try {
        if (id) {
          const res = await goodsApi.deleteSpec({ id })
          message.success(res.msg)
        }
        if (name === 'middleUnitFormData') {
          middleUnitFormData.value = resetMiddleUnitForm()
        }
        if (name === 'largeUnitFormData') {
          largeUnitFormData.value = resetLargeUnitForm()
        }
      } catch (error: any) {
        message.error(error.msg)
        if (name === 'middleUnitFormData') middleUnitFormData.value.checked = true
        if (name === 'largeUnitFormData') largeUnitFormData.value.checked = true
      } finally {
        deleteUnitLoading.value[name] = false
      }
    },
    onCancel: () => {
      if (name === 'middleUnitFormData') middleUnitFormData.value.checked = true
      if (name === 'largeUnitFormData') largeUnitFormData.value.checked = true
    }
  })
}
watch(
  () => [middleUnitFormData.value.checked, largeUnitFormData.value.checked],
  ([middle_checked, large_checked]) => {
    if (!middle_checked && !validateEmptyUnit(middleUnitFormData.value) && defaultUnitData.value?.unit_type !== middleUnitFormData.value.unit_type) {
      deleteSpec('middleUnitFormData', middleUnitFormData.value?.id)
    }
    if (!large_checked && !validateEmptyUnit(largeUnitFormData.value) && defaultUnitData.value?.unit_type !== largeUnitFormData.value.unit_type) {
      deleteSpec('largeUnitFormData', largeUnitFormData.value?.id)
    }
  },
  {
    deep: true,
    flush: 'post'
  }
)

// ========== 自定义事件 ==========
const emit = defineEmits(['reloadList'])
const visible = ref(false)
interface SpecData extends UnitFormData {
  status: number
}
interface RowData extends BaseFormData {
  id: number
  spec: SpecData[]
}
function showDrawer(rowData: RowData) {
  if (rowData) {
    const keys = _.keys(defaultBaseFormData).concat(['id'])
    baseFormData.value = _.pick(rowData, keys) as BaseFormData
    const unitKeys = _.keys(defaultUnitFormData).concat(['id'])
    for (const unitInfo of rowData.spec) {
      if (unitInfo.unit_type === GOODS_UNIT_TYPE.SMALL.value) {
        smallUnitFormData.value = _.pick(unitInfo, unitKeys) as UnitFormData
        smallUnitFormData.value.checked = true
        continue
      }
      if (unitInfo.unit_type === GOODS_UNIT_TYPE.MIDDLE.value) {
        middleUnitFormData.value = _.pick(unitInfo, unitKeys) as UnitFormData
        middleUnitFormData.value.checked = !validateEmptyUnit(middleUnitFormData.value)
        continue
      }
      if (unitInfo.unit_type === GOODS_UNIT_TYPE.LARGE.value) {
        largeUnitFormData.value = _.pick(unitInfo, unitKeys) as UnitFormData
        largeUnitFormData.value.checked = !validateEmptyUnit(largeUnitFormData.value)
        continue
      }
    }
  }
  visible.value = true
}
function closeDrawer() {
  visible.value = false
  baseFormData.value = _.cloneDeep(defaultBaseFormData)
  baseFormRef.value.clearValidate()

  tabKey.value = 'unit'
  smallUnitForm.value.clearValidate()
  smallUnitFormData.value = resetSmallUnitForm()
  middleUnitForm.value.clearValidate()
  middleUnitFormData.value = resetMiddleUnitForm()
  largeUnitForm.value.clearValidate()
  largeUnitFormData.value = resetLargeUnitForm()
}
defineExpose({
  showDrawer
})

// ========== 校验、提交、关闭 ==========
function validateEmptyUnit(unit: UnitFormData) {
  return _(unit)
    .pick(Object.keys(unitRules))
    .every((value) => {
      return value === '' || _.isUndefined(value)
    })
}
function validateAll() {
  const validateTasks = [
    baseFormRef.value.validate().catch(() => {
      return Promise.reject(new Error('请填写基本信息'))
    }),
    smallUnitForm.value.validate().catch(() => {
      return Promise.reject(new Error('请填写小单位信息'))
    })
  ]
  middleUnitFormData.value.checked &&
    validateTasks.push(
      middleUnitForm.value.validate().catch(() => {
        return Promise.reject(new Error('请填写中单位信息'))
      })
    )
  largeUnitFormData.value.checked &&
    validateTasks.push(
      largeUnitForm.value.validate().catch(() => {
        return Promise.reject(new Error('请填写大单位信息'))
      })
    )
  return Promise.all(validateTasks)
}
const onSubmit = async () => {
  try {
    await validateAll()
    const params = Object.assign(baseFormData.value, {
      spec: JSON.stringify(unitFormData.value)
    })
    const methodName = params.id ? 'update' : 'create'
    const res = await goodsApi[methodName](params)
    message.success(res.msg)
    emit('reloadList')
    closeDrawer()
  } catch (error: any) {
    errorSentry.captureError(error)
    message.error(error?.msg ?? error.message)
  }
}

// 表单标题
const formTitle = computed(() => (baseFormData.value.id ? '编辑' : '新增'))
</script>
<style scoped>
:deep(.ant-tabs-nav::before) {
  border-bottom: none;
}
:deep(.ant-table-cell .ant-form-item) {
  margin-bottom: 0;
}
:deep(.ant-space-item) {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  line-height: 1.5;
}
.custom-tab {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  line-height: 1.5;
}
</style>
